/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-06-06 10:31:12
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-06-15 10:04:23
 * @FilePath: \cxl-h5\src\utils\changeImageDirection.ts
 */
export default class ImageDirection {
    //图像方向。 - - 1：未定义， - 0：正向， - 1：逆时针90度， - 2：逆时针180度， - 3：逆时针270度
    direction: number | string | null = 0
    w = 0
    h = 0
    constructor() {}
    init(base64: string, direction: number | string | null, callback = (url: string) => {}) {
        this.direction = direction
        const oImg = new Image()
        oImg.src = base64
        oImg.onload = (res: any) => {
            console.log(res, oImg.naturalHeight, oImg.naturalWidth)
            this.w = oImg.naturalWidth
            this.h = oImg.naturalHeight
            this.createCanvas(oImg, callback)
        }
    }
    createCanvas(img: HTMLImageElement, callback = (url: string) => {}) {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        //根据图片方向设置canvas宽高
        if (this.direction == 0 || this.direction == 2) {
            canvas.width = this.w
            canvas.height = this.h
            if (this.direction == 2) {
                ctx?.translate(this.w, this.h)
                ctx?.rotate(Math.PI)
                ctx?.drawImage(img, 0, 0, this.w, this.h)
            } else {
                ctx?.drawImage(img, 0, 0, this.w, this.h)
            }
        } else if (this.direction == 1 || this.direction == 3) {
            canvas.width = this.h
            canvas.height = this.w
            if (this.direction == 1) {
                ctx?.translate(this.h, 0)
                ctx?.rotate(Math.PI / 2)
                ctx?.drawImage(img, 0, 0, this.w, this.h)
            } else if (this.direction == 3) {
                ctx?.translate(0, this.w)
                ctx?.rotate(-Math.PI / 2)
                ctx?.drawImage(img, 0, 0, this.w, this.h)
            }
        } else {
            canvas.width = this.w
            canvas.height = this.h
            ctx?.drawImage(img, 0, 0, this.w, this.h)
        }
        const str = canvas.toDataURL('jpeg', 1)
        callback(str)
    }
}
